<?php
/**
 * 约课汇总
 * @author a
 *
 */
error_reporting(E_ALL ^ E_NOTICE);
class Summarybook extends CT_Controller{
	
	private $offse = 0;
	private $page_size = 0;
	private $page = 0;
	private $size = 10; //每页显示数量
	private $substr_num = 20;   //列表显示留言数量
	
	function __construct(){
		parent::__construct();
		$this->load->helper("arraytool");   //加载工具
		$this->load->helper("tools_helper");   //加载工具
		$this->t = $this->ct_template;
		
		$this->load->model('order_model');
		$this->load->model('area_model');
		$this->load->model('city_model');
        $this->load->model('course_cate_model');  
        $this->load->model('course_list_model');  
        $this->load->model('course_package_model');
        $this->load->model('nursery_model');
        $this->load->model('book_model');
        $this->load->model('book_member_model');
        $this->load->model('book_evaluate_model');
        $this->load->model('teacher_model');
		
		//分页
		$this->page = $this->input->get('per_page',TRUE) ? intval($this->input->get('per_page',TRUE)) : 1;
		$this->page_size = $this->config->item('per_page')?$this->config->item('per_page'):$this->size;
		$this->offse = ($this->page-1) * $this->page_size;
	
	}
	public function Index(){
		try {
			$fild = 'book.id,book.teacher_id,book_date,book_date_start,book_date_end,message,teacher_msg,book.status,';
			$fild.= 'nursery.title as nursery_title,baby_name';
			$where = $this->search();
            $book_list = $this->book_model->summary_book_list($where,$fild,'id desc',$this->offse,$this->page_size);
            if(empty($book_list))throw new Exception('没有记录');
            
			$total = $this->book_model->summary_book_list($where,'count(1) as num'); //总数
			$pagelink = $this->pagination($total[0]['num'],$this->page_size);
            
            //获取教师
            $where = "id IN (". filterValue($book_list,'teacher_id',true) .")";
            $teacher_list = $this->teacher_model->findAll($where,'id,name as teacher_name');
            $teacher_list = restByKey($teacher_list,'id');
            $book_list = arrayMerge($book_list,'teacher_id',$teacher_list);	//合并
            
            //获取评价
            $where = "book_id IN (". filterValue($book_list,'id',true) .")";
            $book_evaluate_list = $this->book_evaluate_model->findAll($where,'id,message,star');
            $book_evaluate_list = restByKey($book_evaluate_list,'book_id');
            $book_list = arrayMerge($book_list,'id',$book_evaluate_list);	//合并
            
			
			//$this->pr($book_list);
			
		} catch (Exception $e) {
			$error = $e->getMessage();
		}
		$this->t->write_view('content', 'admin/summarybook/index', array(
                'pagelink'     =>  $pagelink,
                'book_list'    =>  $book_list,
                'book_status'  => array('待上课','上课中','已下课','已结束','取消预约'),
                'substr_num'   =>   $this->substr_num,
				'book_total'	=>	$total[0]['num'],
				'error'     =>  empty($error) ? '' : $error,
		), false);
		$this->t->render();
	}
	/**
	 * 检索
	 */
	private function search(){
		try {
			//$this->pr($_SERVER);
			$where = ' 1=1 ';
			if(empty($_REQUEST['search']))throw new Exception();
			if(!empty($_REQUEST['start_time']))$where .= " AND book.book_date >= '".$this->input->get('start_time')."'";
			if(!empty($_REQUEST['stop_time']))$where .= " AND book.book_date <= '".$this->input->get('stop_time')."'";
			if(!empty($_REQUEST['keyword'])){
				$where .= " AND ( nursery.title LIKE '%".$this->input->get('keyword')."%'";
				$where .= " OR book_member.baby_name LIKE '%".$this->input->get('keyword')."%')";
			}
		} catch (Exception $e) {
			//return '';
		}
		return $where;
	}
	/**
	 * 重置预约
	 */
	public function Resetbook(){
		try {
			$book_id = intval($_REQUEST['book_id']);
			if(empty($book_id))throw new Exception('ID为空');
			$book_info = $this->book_model->find(array('id'=>$book_id));
			if(empty($book_info))throw new Exception('不存在');
			
			$form_submit = $this->input->post('form_submit');
			if(!empty($form_submit)){
				$this->load->model('reset_book_model');
				$bool = $this->reset_book_model->insert(array(
						'admin_id'	=>	$this->_uid,
						'book_id'	=>	$book_id,
						'teacher_id'	=>	$book_info['teacher_id'],
						'hours'		=>	1,
						'book_date'	=>	$book_info['book_date'],
						'book_date_start'	=>	$book_info['book_date_start'],
						'book_date_end'	=>	$book_info['book_date_end'],
						'create_date'	=>	date('Y-m-d H:i:s'),
				));
				
				if(empty($bool))throw new Exception('错误');
				$book_time = explode('-',$_REQUEST['book_time']);
				$this->book_model->update(array(
						'teacher_id'	=>	$_REQUEST['teacher_id'],
						'book_date'		=>	$_REQUEST['book_date'],
						'book_date_start'	=>	$book_time[0],
						'book_date_end'		=>	$book_time[1],
				),array('id'=>$book_id));
				
				redirect("admin/summarybook");
				//$this->pr($_REQUEST);
				
			}
			
			//获取教师列表
			$where = array(
					//'nursery_id'=> $course_package_info['nursery_id'],
					'status'    =>1,
			);
			$teacher_list = $this->teacher_model->findAll($where,'id,name,avatar,book_num,explain');
			if(empty($teacher_list))throw new Exception('教师列表为空');
			
			$this->t->write_view('content', 'admin/summarybook/resetbook', array(
					'teacher_list'	=>	$teacher_list,
					'book_info'	=>	$book_info,
					'book_id'	=>	$book_id,
			), false);
			$this->t->render();
			
			
			//$this->pr($book_info);
				
				
			
		} catch (Exception $e) {
			$error = $e->getMessage();
			$this->t->write_view('content', 'admin/msg_error', array(
					'error'     =>  $error,
					'time'  =>  10,
					//'url'   =>  '/admin/book/',
			), false);
			$this->t->render();
		}
	}
	/**
	 * 返回教师可用时间
	 */
	public function Teachertime(){
		try {
			$return = array('code'=>11,'mgs'=>'','list'=>'');
// 			$order_id = intval($this->input->get('order_id'));    //订单ID
// 			if(empty($order_id))throw new Exception('订单ID为空');
	
// 			$course_package_info = $this->IsHours($order_id); //验证课时
	
// 			//session 取出已经选择的课程
// 			$this->load->library('session');
// 			$time_list = $this->session->time_list;
	
// 			//echo '<pre>';print_r($time_list);die();
	
// 			if($course_package_info['hours'] <= count($time_list))
// 				throw new Exception('您的课时已用完');
	
				$this->load->helper("arraytool");   //加载工具
				$teacher_id = intval($this->input->get('teacher_id'));    //获取园所ID
				if(empty($teacher_id))throw new Exception('教师ID为空');
	
				//获取教师时间段
				$this->load->model('Teacher_Work_Time_model');
				$where = array(
						'teacher_id'=>$teacher_id,
						'status'    =>  1,
				);
				$work_time = $this->Teacher_Work_Time_model->findAll($where,'work_week,work_time_start,work_time_end');
				if(empty($work_time))throw new Exception('此教师未设置可用时间段');
				$work_time = restByKey($work_time,'work_week',true);
	
				$data_list = $this->getDateList(30);     //获取30天之后的时间
	
				//合并
				foreach ($data_list as $key=>$val){
					if(!empty($work_time[$val['week']])){
						$data_list[$key]['list'] = $work_time[$val['week']];
					}
				}
	
				//获取该老师已预约的课程
				//$this->load->model('Book_model');
				$where = "teacher_id = '$teacher_id' AND status IN (0,1)";
				$book_list = $this->book_model->findAll($where,'id,book_date,book_date_start,book_date_end');
	
				//取出已选择课程session加入过滤
				if(empty($book_list))$book_list = array();
				if(empty($time_list))$time_list = array();
				$book_list = array_merge($book_list,$time_list);
	
				//echo '<pre>';print_r($book_list);die();
				//过滤已经约课教师
				if(!empty($book_list)){
					foreach ($book_list as $val){
						if(!empty($data_list[$val['book_date']]['list'])){
							$work_time = $data_list[$val['book_date']]['list'];
							foreach ($work_time as $key_work=>$val_work){
								//结束课程的1小时，不可预约
								if($val['book_date_start'] <= $val_work['work_time_start'] && date('H:i:s',strtotime($val['book_date_end'])+3600) >= $val_work['work_time_end']){
									unset($data_list[$val['book_date']]['list'][$key_work]);
								}
							}
						}
					}
				}
	
				//过滤不存在的时间
				foreach ($data_list as $key=>$val){
					if(empty($val['list']))unset($data_list[$key]);
				}
				$tmp = array();
				foreach ($data_list as $key=>$val){
					sort($val['list']);
					$tmp[] = $val;
				}
				
				//存入SESSION
				$this->load->library('session');
				$this->session->set_userdata('data_list',$data_list);
				
				
				$return['code'] = 10;
				$return['list'] = $tmp;
		}catch (Exception $e){
			$return['msg'] = $e->getMessage();
		}
	
		echo json_encode($return);exit();
	}
	/**
	 * 取出时间
	 */
	public function Getsessiontime(){
			//session 取出已经选择的课程
			$this->load->library('session');
			$data_list = $this->session->data_list;
			echo json_encode($data_list);exit();
	}
	/**
	 * 获取时间列表
	 */
	private function getDateList($num = 30){
		$data = array();
		$weekArr=array("周日","周一","周二","周三","周四","周五","周六");
		for ($i=0;$i<$num;$i++){
			$d = date('Y-m-d',mktime(0,0,0,date('m'),date('d')+$i,date('Y')));
			$w = date('w',strtotime($d));
			$data[$d] = array(
					'date'  =>  $d,
					'week'  =>  $w,
					'week_name' =>  $weekArr[$w],
			);
		}
		//排除节假日
		$this->load->model('holiday_time_model');
		$holiday_list = $this->holiday_time_model->findAll(array('status'=>1),'holiday');
		if(!empty($holiday_list)){
			$tmp = array();
			foreach ($holiday_list as $key=>$val){
				$tmp[] = $val['holiday'];
			}
			foreach ($data as $key=>$val){
				if(in_array(mb_substr($key,5),$tmp))unset($data[$key]);
			}
		}
		return $data;
	}
}


























